import os
startSvgTag = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="240px" height="240px" viewBox="0 0 240 240">"""

endSvgTag = """</svg>"""
dir_name='your_SVGs_here'

def img_path_to_base64(image_path):
    with open(image_path, 'rb') as f:
        image = f.read()
        image_base64 = str(base64.b64encode(image), encoding='utf-8')
    return image_base64

import base64

def img_to_base64(image):
    image_base64 = str(base64.b64encode(image), encoding='utf-8')
    return image_base64

def str_to_base64(string):
    
    str3 = string.encode(encoding ='utf-8',errors = 'strict');
    str4= base64.b64encode(str3)
    enstr = base64.b64decode(str4.decode())
    return enstr

if not os.path.exists(dir_name):
    os.mkdir('your_SVGs_here')
for file_path in os.listdir("."):
    if file_path.endswith(".png"):
        pngFile = open(file_path, 'rb')
        # rb 转化 base64 
        # AttributeError: 'bytes' object has no attribute 'encode'
        # base64data = pngFile.read().encode("base64").replace('\n', '')
        # LookupError: 'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs
        data=pngFile.read()
        # base64data = pngFile.read().decode("base64").replace('\n', '')
        # base64data =str_to_base64(data).replace('\n', '')
        # img_path_to_base64(files)
        # base64data=img_to_base64(pngFile)
        base64data=img_to_base64(data)
        # 成decode就
        # https://blog.csdn.net/qq_42363032/article/details/118361728
        base64String = '<image xlink:href="data:image/png;base64,{0}" width="240" height="240" x="0" y="0" />'.format(
            base64data)
        out_path=os.getcwd()+ "/your_SVGs_here/" +os.path.splitext(file_path)[0] + ".svg"
        if os.path.exists(out_path):
            print(out_path,"已经存在，不用再转化")
            continue
        # f = open(os.getcwd()+ "/your_SVGs_here/" +os.path.splitext(file_path)[0] + ".svg", 'w')
        f = open(out_path, 'w')
        f.write(startSvgTag + base64String + endSvgTag)
        print ('Converted ' + file_path + ' to ' + os.path.splitext(file_path)[0] + ".svg")

# 网上的转化貌似就是用的这个方法。。 这能用吗。。